package com.demo.socket;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;

public class ServerSocketDemo {
    public static void main(String[] args) throws IOException {

        int readCount = 1;
        String rcvFilePath = System.getProperty("user.dir") + "/netURL/target/s1.txt";
        //创建服务端,监听端口
        ServerSocket serverSocket = new ServerSocket(9000);
        while (true) {
            //获取客户端Socket
            Socket socket = serverSocket.accept();
//            serverSocket.setSoTimeout(5000);
            System.out.println("有客户端来了");
            //获取客户端输入流
            InputStream ins = socket.getInputStream();
            FileOutputStream fos = new FileOutputStream(new File(rcvFilePath));
            //创建缓冲区关联输入流和输出流
            byte[] b = new byte[1024];
            int len = 0;
            System.out.println("开始接收");
            while ((len = ins.read(b)) != -1) {
                fos.write(b, 0, len);
                System.out.println("第" + readCount++ + "次读取len:" + len);
            }
            System.out.println(len);
            System.out.println("接收完成");
            fos.close();
            ins.close();
            socket.close();
        }
    }
}
